import pandas as pd
import matplotlib.pyplot as plt
from multiprocessing import Process, Queue
import time
import os
from sklearn.linear_model import LinearRegression
from sklearn.ensemble import IsolationForest
from xgboost import XGBRegressor
import numpy as np
from reportlab.lib.pagesizes import letter
from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, Image
from reportlab.lib.styles import getSampleStyleSheet

class AutonomousDataPreprocessor:
    """自主数据预处理智能体"""
    def __init__(self, input_queue, output_queue):
        self.input = input_queue
        self.output = output_queue
        self.learned_parameters = {}

    def clean_data(self, data):
        """自主数据清洗"""
        # 自动处理缺失值
        if data.isnull().sum().sum() > 0:
            data = data.dropna()
            self.learned_parameters['missing_value_strategy'] = 'drop'
        
        # 自动检测日期格式
        try:
            data['日期'] = pd.to_datetime(data['日期'])
        except:
            data['日期'] = pd.to_datetime(data['日期'], errors='coerce')
        
        return data

    def run(self):
        while True:
            task = self.input.get()
            if task == 'STOP':
                break
            
            try:
                data = pd.read_csv(task['file_path'])
                data = self.clean_data(data)
                self.output.put({
                    'data': data,
                    'type': 'preprocessed',
                    'agent': 'preprocessor'
                })
            except Exception as e:
                self.output.put({
                    'error': str(e),
                    'type': 'error',
                    'agent': 'preprocessor'
                })

class AnomalyDetector:
    """异常检测智能体"""
    def __init__(self, input_queue, output_queue):
        self.input = input_queue
        self.output = output_queue
        
    def detect_anomalies(self, data):
        """使用Isolation Forest检测异常"""
        features = data[['销售额', '客户评分']].values
        clf = IsolationForest(contamination=0.05)
        preds = clf.fit_predict(features)
        data['异常标记'] = preds == -1
        return data

    def run(self):
        while True:
            task = self.input.get()
            if task == 'STOP':
                break
                
            if 'data' in task:
                data = self.detect_anomalies(task['data'])
                self.output.put({
                    'data': data,
                    'type': 'anomaly_checked',
                    'agent': 'anomaly_detector'
                })

class AutonomousAnalyst:
    """自主分析智能体"""
    def __init__(self, input_queue, output_queue):
        self.input = input_queue
        self.output = output_queue
        self.learned_models = {}

    def train_trend_model(self, data):
        """使用XGBoost训练销售趋势预测模型"""
        data['day_num'] = (data['日期'] - data['日期'].min()).dt.days
        data['month'] = data['日期'].dt.month
        data['weekday'] = data['日期'].dt.weekday
        
        # 多维度特征
        X = data[['day_num', 'month', 'weekday']].values
        y = data['销售额'].values
        
        model = XGBRegressor()
        model.fit(X, y)
        self.learned_models['trend'] = model
        return model

    def customer_segmentation(self, data):
        """客户细分分析"""
        from sklearn.cluster import KMeans
        features = data[['销售额', '客户评分']].values
        kmeans = KMeans(n_clusters=3)
        data['客户群体'] = kmeans.fit_predict(features)
        return data

    def seasonal_analysis(self, data):
        """季节性分析"""
        monthly = data.groupby(data['日期'].dt.month)['销售额'].sum()
        return monthly.to_dict()

    def run(self):
        while True:
            task = self.input.get()
            if task == 'STOP':
                break
            
            if 'data' in task:
                data = task['data']
                
                # 基础分析
                stats = {
                    'total_sales': data['销售额'].sum(),
                    'avg_rating': data['客户评分'].mean(),
                    'product_stats': data.groupby('产品')['销售额'].agg(['sum', 'mean', 'count']).to_dict()
                }
                
                # 趋势预测
                trend_model = self.train_trend_model(data)
                future_days = 30
                prediction = trend_model.predict([[data['day_num'].max() + future_days]])
                
                self.output.put({
                    'stats': stats,
                    'prediction': prediction[0],
                    'type': 'analysis',
                    'agent': 'analyst'
                })

class ReportGenerator:
    """PDF报告生成智能体"""
    def __init__(self, input_queue):
        self.input = input_queue
        self.output_dir = 'reports'
        
    def generate_pdf(self, stats, images):
        """生成PDF分析报告"""
        os.makedirs(self.output_dir, exist_ok=True)
        filename = f"{self.output_dir}/analysis_report.pdf"
        
        doc = SimpleDocTemplate(filename, pagesize=letter)
        styles = getSampleStyleSheet()
        story = []
        
        # 添加标题
        story.append(Paragraph("市场营销分析报告", styles['Title']))
        story.append(Spacer(1, 12))
        
        # 添加统计结果
        story.append(Paragraph("销售统计", styles['Heading2']))
        stats_text = f"""
        总销售额: {stats['total_sales']}元
        平均评分: {stats['avg_rating']:.2f}
        预测销售额: {stats['prediction']:.2f}元
        """
        story.append(Paragraph(stats_text, styles['Normal']))
        story.append(Spacer(1, 12))
        
        # 添加图表
        for img in images:
            story.append(Paragraph(img['title'], styles['Heading3']))
            story.append(Image(img['path'], width=400, height=300))
            story.append(Spacer(1, 12))
            
        doc.build(story)
        return filename

    def run(self):
        while True:
            task = self.input.get()
            if task == 'STOP':
                break
                
            if 'stats' in task:
                images = [
                    {'path': 'reports/sales_trend.png', 'title': '销售趋势'},
                    {'path': 'reports/product_dist.png', 'title': '产品分布'}
                ]
                self.generate_pdf(task['stats'], images)

class AutonomousVisualizer:
    """自主可视化智能体"""
    def __init__(self, input_queue, output_queue):
        self.input = input_queue
        self.output = output_queue
        self.output_dir = 'reports'

    def generate_visualizations(self, data):
        """生成自主可视化报告"""
        os.makedirs(self.output_dir, exist_ok=True)
        
        # 销售趋势图
        data.set_index('日期', inplace=True)
        monthly_sales = data.resample('M')['销售额'].sum()
        fig, ax = plt.subplots(figsize=(10, 6))
        monthly_sales.plot(ax=ax, title='月度销售趋势')
        fig.savefig(f'{self.output_dir}/sales_trend.png')
        plt.close(fig)
        
        # 产品分布图
        product_sales = data.groupby('产品')['销售额'].sum()
        fig, ax = plt.subplots(figsize=(10, 6))
        product_sales.plot(kind='bar', ax=ax, title='产品销售额分布')
        fig.savefig(f'{self.output_dir}/product_dist.png')
        plt.close(fig)
        
        # 异常数据可视化
        if '异常标记' in data.columns:
            anomalies = data[data['异常标记']]
            if not anomalies.empty:
                fig, ax = plt.subplots(figsize=(10, 6))
                ax.scatter(data['销售额'], data['客户评分'], c='blue', label='正常')
                ax.scatter(anomalies['销售额'], anomalies['客户评分'], c='red', label='异常')
                ax.set_title('异常数据检测')
                ax.set_xlabel('销售额')
                ax.set_ylabel('客户评分')
                ax.legend()
                fig.savefig(f'{self.output_dir}/anomalies.png')
                plt.close(fig)

    def run(self):
        while True:
            task = self.input.get()
            if task == 'STOP':
                break
            
            if 'data' in task:
                self.generate_visualizations(task['data'])

class AutonomousCoordinator:
    """全自主协调智能体"""
    
    def __init__(self):
        self.queues = {
            'preprocessor': Queue(),
            'anomaly_detector': Queue(),
            'analyst': Queue(),
            'visualizer': Queue(),
            'report_generator': Queue(),
            'coordinator': Queue()
        }
        
        # 创建智能体
        self.agents = [
            Process(target=AutonomousDataPreprocessor(
                self.queues['coordinator'],
                self.queues['preprocessor']).run),
            Process(target=AnomalyDetector(
                self.queues['preprocessor'],
                self.queues['anomaly_detector']).run),
            Process(target=AutonomousAnalyst(
                self.queues['anomaly_detector'],
                self.queues['analyst']).run),
            Process(target=AutonomousVisualizer(
                self.queues['analyst'],
                self.queues['visualizer']).run),
            Process(target=ReportGenerator(
                self.queues['visualizer']).run)
        ]
        
        # 监控状态
        self.last_analysis_time = None
        self.data_file = 'sample_data.csv'
        self.file_mod_time = os.path.getmtime(self.data_file)

    def start_agents(self):
        """启动所有智能体"""
        for agent in self.agents:
            agent.start()
        print("所有智能体已启动")

    def analyze_data(self, file_path):
        """执行数据分析"""
        self.queues['coordinator'].put({'file_path': file_path})
        
        while True:
            result = self.queues['visualizer'].get()
            
            if 'stats' in result:
                print("\n=== 自主分析结果 ===")
                print(f"总销售额: {result['stats']['total_sales']}元")
                print(f"平均评分: {result['stats']['avg_rating']:.2f}")
                print(f"30天后预测销售额: {result['prediction']:.2f}元")
                
                # 显示异常数据
                if 'anomalies' in result['stats']:
                    print("\n=== 异常数据 ===")
                    print(f"检测到 {len(result['stats']['anomalies'])} 条异常记录")
                    print(result['stats']['anomalies'][['日期', '产品', '销售额', '客户评分']])
                
                print("\n产品统计:")
                print(pd.DataFrame(result['stats']['product_stats']))
                
                print("\n报告已生成: reports/analysis_report.pdf")
                self.last_analysis_time = time.time()
                break

    def monitor_new_data(self):
        """监控新数据"""
        current_mod_time = os.path.getmtime(self.data_file)
        if current_mod_time > self.file_mod_time:
            print("\n检测到数据更新，重新分析...")
            self.file_mod_time = current_mod_time
            self.analyze_data(self.data_file)

    def stop_agents(self):
        """停止所有智能体"""
        for q in self.queues.values():
            q.put('STOP')
        for agent in self.agents:
            agent.join()
        print("所有智能体已停止")